<?php

namespace plugin\ycMassage\app\admin\controller;

use plugin\ycMassage\app\BaseController;
use app\common\trait\plugin\TagsTrait;
use plugin\ycMassage\app\model\PluginTags;
use support\Request;

/**
 * 单页系统
 *
 * @author 贵州猿创科技有限公司
 * @Email 416716328@qq.com
 * @DateTime 2023-03-07
 */
class TagsController extends BaseController
{
    use TagsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 模型
     * @var PluginTags
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
        $this->model = new PluginTags;
    }
    public function save(Request $request)
    {
        if ($request->method() == 'POST') {
            $post = $request->post();
            $model = $this->model->where(['saas_appid' => $request->saas_appid, 'name' => $post['name']])->find();
            if (!$model) {
                $model = new PluginTags;
                $model->saa_appid = $request->saas_appid;
            }
            $model->status = '20';

            # 数据验证
            if (empty($post['title'])) {
                return $this->fail('请输入标题名称');
            }
            if (empty($post['name'])) {
                return $this->fail('请输入标签名称');
            }
            if (!$model->save($post)) {
                return $this->fail('保存失败');
            }
            return $this->success('保存成功');
        }
        $name = $request->get('tag_name');
        $model = $this->model->where(['saas_appid' => $request->saas_appid, 'name' => $name])->find();
        $form = $this->getFormView()->setMethod('POST');
        if ($model) {
            $form->setData($model);
        } else {
            $form->setFormData(['name' => $name, 'status' => '20']);
        }
        $data = $form->create();
        return $this->successRes($data);
    }
}
